<template>
    <div id="map_box"></div>
</template>

<script>
import * as echarts from 'echarts';
import chinaMap from '@/common/map_china.json'; // 请确保地图JSON路径正确
import { getCityListApi } from '@/api/request';

export default {
    name: 'CityMap',
    data() {
        return {
            mapChart: null,
            cityList: [],
            intervalId: null,
            loading: false,
            index: 0,
        }
    },
    mounted() {
        this.initMap();
        this.getCityList();
        // 监听窗口变化
        window.addEventListener('resize', () => this.mapChart?.resize());
    },
    methods: {
        initMap() {
            // 销毁已有实例避免重复初始化
            if (this.mapChart) {
                this.mapChart.dispose();
            }
            this.mapChart = echarts.init(document.getElementById('map_box'));
            echarts.registerMap('china', chinaMap);

            this.mapOption = {
                title: {
                    text: '达人入驻城市',
                    left: '2%',
                    top: '2%',
                    textStyle: {
                        color: '#00FFFF',
                        fontSize: 20,
                        fontWeight: 'bold',
                        textShadowColor: '#00FFFF',
                        textShadowBlur: 10,
                    }
                },
                visualMap: {
                    show: true,
                    type: 'piecewise',
                    pieces: [
                        { min: 1500, color: '#FF4500', label: '1500人以上' },
                        { min: 1000, max: 1499, color: '#FFA500', label: '1000-1499人' },
                        { min: 500, max: 999, color: '#FFFF00', label: '500-999人' }
                    ],
                    inRange: {
                        color: ['lightskyblue', 'yellow', 'orangered']
                    },
                    textStyle: {
                        color: '#fff'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    backgroundColor: 'rgba(30, 42, 86, 0.95)',
                    borderColor: '#00FFFF',
                    borderWidth: 2,
                    textStyle: {
                        color: '#fff',
                        fontSize: 14,
                    },
                    formatter: (p) => {
                        if (!p || !p.data || p.data.value == null) return '';
                        return `📍 <b style="color: #fff">${p.name}</b><br/>
                                📊 入驻达人：<b>${p.data.value}人</b><br/>
                                🏆 城市等级：<b>${p.data.level}</b><br/>
                                🏅 下单量：<b>${p.data.value}</b><br/>
                                💰 总金额：<b>${p.data.value}元</b>`;
                    }
                },
                series: [{
                    type: 'map',
                    mapType: 'china',
                    zoom: 1.35,
                    top: '18%',
                    itemStyle: {
                        areaColor: '#2099C7',
                        borderColor: '#00FFFF',
                        emphasis: {
                            areaColor: '#3E7FF3',
                            borderColor: '#21C1FB',
                            borderWidth: 3,
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 255, 255, 0.5)',
                            transitionDuration: 0.5
                        },
                    },
                    select: {
                        itemStyle: {
                            areaColor: '#FF6347',
                            borderColor: '#FF0000',
                            borderWidth: 4
                        }
                    },
                    data: this.cityList,
                    selectMode: 'single'
                }]
            };

            this.mapChart.setOption(this.mapOption);

            // 绑定点击事件
            this.mapChart.on('click', (params) => {
                if (params.componentType === 'series') {
                    this.mapChart.dispatchAction({
                        type: 'select',
                        seriesIndex: 0,
                        name: params.name
                    });
                }
            });
            // 鼠标移入事件
            this.mapChart.on('mouseover', (params) => {
                if (this.intervalId) {
                    // 取消所有城市的提示
                    this.mapChart.dispatchAction({
                        type: 'hideTip',
                        seriesIndex: 0,
                        name: this.cityList[this.index].name
                    });
                    // 取消当前城市的提示
                    this.mapChart.dispatchAction({
                        type: 'downplay',
                        seriesIndex: 0,
                        name: this.cityList[this.index].name
                    });
                    clearInterval(this.intervalId);
                }

                if (params.componentType === 'series') {
                    this.mapChart.dispatchAction({
                        type: 'highlight',
                        seriesIndex: 0,
                        name: params.name
                    });
                }
            });
            // 鼠标移出事件
            this.mapChart.on('mouseout', (params) => {
                //   取消当前城市的提示
                this.mapChart.dispatchAction({
                    type: 'hideTip',
                    seriesIndex: 0,
                    name: params.name
                });
                this.mapChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0,
                    name: params.name
                });
                this.highlightCity();
            });
            // 自动高亮城市
            this.highlightCity();
        },

        // 自动高亮城市逻辑（修复索引越界）
        highlightCity() {
            if (!this.mapChart || this.cityList.length === 0) return;

            // 清除已有定时器
            if (this.intervalId) {
                clearInterval(this.intervalId);
            }


            this.intervalId = setInterval(() => {
                // 先取消上一个城市的高亮
                this.mapChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0,
                    name: this.cityList[this.index].name
                });


                // 更新索引（循环逻辑修正）
                this.index = (this.index + 1) % this.cityList.length;

                // 当前下标高亮
                this.mapChart.dispatchAction({
                    type: 'highlight',
                    seriesIndex: 0,
                    name: this.cityList[this.index].name
                });

                // 显示提示信息
                this.mapChart.dispatchAction({
                    type: 'showTip',
                    seriesIndex: 0,
                    name: this.cityList[this.index].name
                });
            }, 2000);
        },

        async getCityList() {
            try {
                this.loading = true;
                const res = await getCityListApi();
                this.cityList = res.rows.map(city => ({
                    name: city.name || '未知城市',
                    value: city.value || Math.floor(Math.random() * 2000) + 500,
                    level: city.level || Math.floor(Math.random() * 3) + 1, // 确保等级不为0
                }));
                this.initMap();
            } catch (error) {
                console.log('获取入驻城市失败', error);
            } finally {
                this.loading = false;
            }
        },
    },
    beforeDestroy() {
        // 清理资源
        if (this.mapChart) {
            this.mapChart.dispose();
        }
        if (this.intervalId) {
            clearInterval(this.intervalId);
        }
        window.removeEventListener('resize', () => this.mapChart?.resize());
    }
}
</script>

<style scoped>
#map_box {
    width: 100%;
    height: 100%;
    border-radius: inherit;
}
</style>